package com.kaifamiao.chars;

public class CharacterSequence implements CharSequence {

    private final char[] value;

    public CharacterSequence( char[] chars ) {
        super();
        // 创建新数组
        value = new char[ chars.length ];
        // 将 chars 数组中所有字符拷贝到 value 数组中
        System.arraycopy( chars , 0 , value, 0 , chars.length);
    }

    @Override
    public int length() {
        return value.length;
    }

    @Override
    public char charAt(int index) {
        if( index < 0 || index > value.length - 1 ) {
            throw new IndexOutOfBoundsException("出轨了");
        }
        return value[index];
    }

    @Override
    public CharSequence subSequence(int start, int end) {
        if( start < 0 || end > value.length || end <= start ) {
            throw new IllegalArgumentException("参数不合适");
        }
        int length = end - start ;
        char[] chars = new char[ length ];
        System.arraycopy( value, start, chars, 0, length );
        CharSequence cs = new CharacterSequence( chars );
        return cs;
    }

    @Override
    public String toString() {
        String s = "";
        for (int i = 0; i < value.length; i++) {
            char ch = value[i];
            s += ch;
        }
        return s;
    }
}
